var memberServiceNative = require('../services/memberService');
var storeServiceNative = require('../services/storeService');
var OAuth = require('wechat-oauth');
var errorHandler = require('../common/errorHandler');
var async = require("async");

var BindMemberController = {
    getBindMember: function (req, res, next) {
        var memberService = errorHandler.errorToResponse(req, res, memberServiceNative);

        memberService.getUserByOpenId(req.params.id, req.query.sns, req.query.openId, function (err, data) {
            if (err || !data) return res.status(400).json({error: '尚未绑定', code: 'not-bound'});
            res.send(data);
        });
    },
    getOpenId: function (req, res, next) {
        var storeService = errorHandler.errorToResponse(req, res, storeServiceNative);

        if (req.query.code == 'test') return res.send({openid: 'openid'});
        var storeId = req.params.id;
        storeService.getMstoreSettings(storeId, function (err, settings) {
            if (!settings) {
                return res.send("");
            }
            var oauth = new OAuth(!settings.sub_wechat_appid ? settings.wechat_appid : settings.sub_wechat_appid,
                !settings.sub_wechat_appsecret ? settings.wechat_appsecret : settings.sub_wechat_appsecret);
            console.log("settings=" , settings);
            console.log("oauth=" ,oauth);
            oauth.getAccessToken(req.query.code, function (err, ret) {
                if (err) return res.send("");
                res.send(ret.data);
            })
        })
    },
    getMemberBindList: function (req, res, next) {
        var memberId = req.params.id;
        var storeId = req.params.storeId;
        var bindList = [];
        async.series([
            function (cb) {
                storeServiceNative.getStoreById(storeId, null, function (err, data) {
                    if (err) {
                        return res.status(400).json({error: '店铺错误'});
                    }
                    cb(err, data);
                })
            },
            function (cb) {
                memberServiceNative.getBindList(storeId, memberId, function (err, data) {
                    if (err) {
                        return res.status(400).json({error: '参数错误'});
                    }
                    bindList = data;
                    cb(err, data);
                })
            }
        ], function (err, result) {
            res.send(bindList);
        })
    },
    unBindMember: function (req, res, next) {
        var bindId = req.params.id;
        memberServiceNative.deleteBind(bindId, function (err, data) {
            if (err) {
                return res.status(400).json({error: '取消绑定失败'});
            }
            return res.send();
        })
    }
}


module.exports = BindMemberController;
